/**
 * @filename:TransferServiceImpl Dec 15, 2023
 * @project Wonder Vue Admin Api  1.1.0
 * Copyright(c) 2022 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.app.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.*;
import com.wonder.app.service.InventoryService;
import com.wonder.app.service.MaterialService;
import com.wonder.app.service.TransferDetailService;
import com.wonder.app.service.TransferService;
import com.wonder.app.request.TransferRequest;
import com.wonder.bean.kingdee.xqc.BillMaterial;
import com.wonder.common.exception.CustomException;
import com.wonder.common.utils.DateUtils;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.common.AjaxResult;

import java.util.*;

import com.wonder.constant.BillEvent;
import com.wonder.constant.BillType;
import com.wonder.constant.IXqcConst;
import jnr.ffi.annotations.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.jsf.FacesContextUtils;

import javax.servlet.http.HttpServletRequest;

/**   
 * @Description:TODO(网页调拨服务实现)
 *
 * @version: 1.1.0
 * @author: Wonder
 * 
 */
@Service
public class TransferServiceImpl  extends ServiceImpl<TransferDao, Transfer> implements TransferService  {
	private static final Logger _logger = LoggerFactory.getLogger(TransferServiceImpl.class);
	@Autowired
	private TransferDao transferDao;

	@Autowired
	private TransferDetailDao transferDetailDao;

	@Autowired
	private InventoryDao inventoryDao;

	@Autowired
	private TransferDetailService transferDetailService;

	@Autowired
	private TransferService transferService;

	@Autowired
	private InventoryService inventoryService;

	@Autowired
	private MaterialService materialService;

	@Autowired
	private MaterialDao materialDao;

	@Autowired
	private StockListDao stockListDao;

	@Autowired
	private ProppbomDao proppbomDao;

	@Autowired
	private ProppbomlistDao proppbomlistDao;



	/**
     * 验证网页调拨信息
     * 
     * @param transfer
     * @param type
     * @return String
     */
    @Override
    public String validate(Transfer transfer,String type){
    
    
       return "";
    }
    
    
    /**
	 * Description:网页调拨分页返回
	 * @param request //检索条件
	 * @param page //分页参数
	 * @return IPage<Transfer>   //分页记录
	 */
	@Override 
	public IPage<Transfer> selectList(TransferRequest request, Page<Transfer> page){
	    LambdaQueryWrapper<Transfer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
	    
	    if (null != request.getBillNo()) {
	       lambdaQueryWrapper.like(Transfer::getBillNo, request.getBillNo());
	      }

		if (null != request.getCreateTime()){
			Date[] createTime = request.getCreateTime();
			if(createTime.length > 0)
				lambdaQueryWrapper.ge(Transfer::getCreateDate, createTime[0]);
			if(createTime.length == 2)
				lambdaQueryWrapper.le(Transfer::getCreateDate, DateUtils.dateToStr(createTime[1],"yyyy-MM-dd") + " 23:59:59");
		}
		lambdaQueryWrapper.orderByDesc(Transfer::getId);	
		Page<Transfer> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
		return selectPage;
    }

	@Override
	public VtuzxMap getDetail(Map<String, Object> map) {
		Long id = Long.parseLong(map.get("id").toString());
		String billNo = map.get("billNo").toString();
		VtuzxMap data = new VtuzxMap();
		Transfer header = transferDao.selectOne(new QueryWrapper<Transfer>().eq("id", id));

		List<TransferDetail> dataList = transferDetailDao.selectList(new QueryWrapper<TransferDetail>().eq("billNo", billNo));
		data.append("header",header)
				.append("dataList",dataList);

		return data;

	}

	@Override
	public Map<String, Object> getMaterialFromStock(Map<String, Object> map) {
		String materialNo = VtuzxUtil.getString(map,"materialNo");
		String batchNo = VtuzxUtil.getString(map,"batchNo");
		String stockNo = VtuzxUtil.getString(map,"stockNo");
		String locationNo = VtuzxUtil.getString(map,"locationNo");
		QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
		if (!VtuzxUtil.isEmpty(materialNo)){
			wrapper.eq("FMaterialNumber",materialNo);
		}
		if (!VtuzxUtil.isEmpty(batchNo)){
			wrapper.like("flot",batchNo);
		}
		if (!VtuzxUtil.isEmpty(stockNo)){
			wrapper.eq("FStockNumber",stockNo);
		}
		wrapper.gt("Fqty",0);

		List<Inventory> inventoryList = inventoryDao.selectList(wrapper);
		Map<String,Object> data = new HashMap<>();
		data.put("dataList",inventoryList);
		return data;
	}

	@Override
	public VtuzxMap updateTransfer(String userName,Long user_id, Map<String, Object> map) throws Exception {
		List<Map<String,Object>> dataList = VtuzxUtil.getObject(map,"data");
		String billNo = VtuzxUtil.getString(map,"billNo");
		String remark = VtuzxUtil.getString(map,"remark");
		List<TransferDetail> insertDetail = new ArrayList<>();//添加到详情表的数据
		for (Map<String,Object> data : dataList){
			String materialNo = VtuzxUtil.getString(data,"materialNo");
			String materialName = VtuzxUtil.getString(data,"materialName");
			String specification = VtuzxUtil.getString(data,"specification");
			String batchNo = VtuzxUtil.getString(data,"flot");
			Date produceDate = VtuzxUtil.parseDate(VtuzxUtil.getString(data,"produceDate"));
			Date expiryDate = VtuzxUtil.parseDate(VtuzxUtil.getString(data,"expiryDate"));
			String unit = VtuzxUtil.getString(data,"unit");
			String ownerName = VtuzxUtil.getString(data,"ownerName");//货主
			String stockNo = VtuzxUtil.getString(data,"srcStockNo");
			String stockName = VtuzxUtil.getString(data,"srcStockName");
			String toStockNo = VtuzxUtil.getString(data,"destStockNo");
			String toStockName = VtuzxUtil.getString(data,"destStockName");
			Long detailId = VtuzxUtil.getLong(data,"id");
			double transferCount = VtuzxUtil.getDouble(data,"fqty");
			//查询调拨的物料是否启用批次
			Material material = materialDao.selectOne(new QueryWrapper<Material>().eq("FNUMBER", materialNo));
			TransferDetail transferDetail = new TransferDetail();
			transferDetail.setId(detailId);
			transferDetail.setBillNo(billNo);
			transferDetail.setMaterialNo(materialNo);
			transferDetail.setMaterialName(materialName);
			transferDetail.setSpecification(specification);
			transferDetail.setFlot(batchNo);
			transferDetail.setProduceDate(produceDate);
			transferDetail.setExpiryDate(expiryDate);
			transferDetail.setUnit(unit);
			transferDetail.setOwnerOutId(ownerName);
			transferDetail.setSrcStockNo(stockNo);
			transferDetail.setSrcStockName(stockName);
			transferDetail.setDestStockNo(toStockNo);
			transferDetail.setDestStockName(toStockName);
			transferDetail.setFqty(transferCount);
			transferDetail.setCreateUserId(user_id);
			transferDetail.setCreateUserName(userName);
			if(null != material){
				transferDetail.setIsProduce(material.getFIsProduce());
				transferDetail.setIsFlot(material.getFIsFlot());
			}

			insertDetail.add(transferDetail);
		}
		boolean detailSave = transferDetailService.saveOrUpdateBatch(insertDetail);
		Transfer transfer = transferDao.selectOne(new QueryWrapper<Transfer>().eq("billNo", billNo));
		transfer.setBillNo(billNo);
		transfer.setUpdateUserName(userName);
		transfer.setNote(remark);
		transfer.setStatus("save");
		boolean save = transferService.saveOrUpdate(transfer);
		return new VtuzxMap("res",save && detailSave );
	}

	@Override
	public Boolean savePickMaterial(JSONObject map) throws Exception{
		//获取所有的物料信息
		String billNo = IXqcConst.createBillNo(BillType.DBRK);
		List<TransferDetail> insertDetail = new ArrayList<>();//添加到调拨详情表的数据
		String userName = map.getStr("userName");//用户名
		Long userId =  map.getLong("userId");
		JSONArray jsonArray =  map.getJSONArray("material");
		String taskBillNo = map.getStr("taskBillNo");//任务单号
		boolean detailSave = true;
		boolean save = true;
		//循环物料添加调拨详情信息
		for (int i = 0; i < jsonArray.size(); i++){
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			String materialNo = jsonObject.getStr("materialNo");
			String stockNo = jsonObject.getStr("stockNo");
			double count = jsonObject.getDouble("count");
			String workShop = jsonObject.getStr("workShop");
			Inventory inventory = inventoryDao.selectOne(new QueryWrapper<Inventory>().eq("FMaterialNumber", materialNo).eq("FStockNumber", stockNo));
			if (null != inventory){
				double inventoryCount = inventory.getFqty();
				if (inventoryCount < count){
					throw new Exception(String.format("物料:%s,库存不足",materialNo));
				}
				String materialName = inventory.getFMaterialName();
				String specification = inventory.getFSpecification();
				String batchNo = inventory.getFlot();
				Date produceDate = inventory.getFProduceDate();
				Date expiryDate = inventory.getFExpiryDate();
				String unit = inventory.getFunit();
				String stockName = inventory.getFStockName();
				//全都调拨到研发仓库
				String toStockNo = "10";
				String toStockName = "研发库";
				boolean isFlot = inventory.getIsFlot();
				boolean isProduce = inventory.getIsProduce();

				TransferDetail transferDetail = new TransferDetail();
				transferDetail.setBillNo(billNo);
				transferDetail.setMaterialNo(materialNo);
				transferDetail.setMaterialName(materialName);
				transferDetail.setSpecification(specification);
				transferDetail.setFlot(batchNo);
				transferDetail.setProduceDate(produceDate);
				transferDetail.setExpiryDate(expiryDate);
				transferDetail.setUnit(unit);

				transferDetail.setSrcStockNo(stockNo);
				transferDetail.setSrcStockName(stockName);
				transferDetail.setDestStockNo(toStockNo);
				transferDetail.setDestStockName(toStockName);
				transferDetail.setWorkShop(workShop);//车间
				transferDetail.setFqty(count);
				transferDetail.setCreateUserId(userId);
				transferDetail.setCreateUserName(userName);
				transferDetail.setIsFlot(isFlot);
				transferDetail.setIsProduce(isProduce);
				insertDetail.add(transferDetail);
			} else {
				throw new Exception(String.format("货品%s不存在",materialNo));
			}


		}
		//先保存详情表数据
		detailSave = transferDetailService.saveBatch(insertDetail);
		Transfer transfer = new Transfer();
		transfer.setBillNo(billNo);
		transfer.setCreateUserName(userName);
		transfer.setCreateUserId(userId);
		transfer.setNote("领料调拨");
		transfer.setStatus("unAudit");
		transfer.setTaskBillNo(taskBillNo);
		//保存外层表数据
		save = transferService.save(transfer);
		//审核调拨单(只增加调入仓库的库存,不扣减库存)
		try {
			auditTransfer(userName,userId,billNo);
		} catch (Exception e){
			throw new CustomException(e.getMessage());
		}


		return detailSave && save;
	}

	/**
	 * 审核调拨单
	 */
	public boolean auditTransfer(String userName,Long user_id, String billNo ) throws Exception{
		List<BillMaterial> addMaterialList = new ArrayList<>();//调入仓库的集合
		List<BillMaterial> reduceMaterialList = new ArrayList<>();//调出仓库的集合
		List<TransferDetail> transferDetailList = transferDetailDao.selectList(new QueryWrapper<TransferDetail>().eq("billNo", billNo));

		boolean flag = true;
		for (TransferDetail data : transferDetailList){
			String materialNo = data.getMaterialNo();
			String materialName = data.getMaterialName();
			String specification = data.getSpecification();
			String batchNo = data.getFlot();
			Date produceDate = data.getProduceDate();
			Date expiryDate = data.getExpiryDate();
			String unit = data.getUnit();
			String workShop = data.getWorkShop();//货主
			String stockNo = data.getSrcStockNo();
			String stockName = data.getSrcStockName();
			String toStockNo = data.getDestStockNo();
			String toStockName = data.getDestStockName();
			double transferCount = data.getFqty();
			boolean isProduce = data.getIsProduce();
			boolean isFlot = data.getIsFlot();

			//判断仓库不能为空
			if (VtuzxUtil.isEmpty(stockNo) || VtuzxUtil.isEmpty(toStockNo)){
				throw new Exception("仓库不能为空");
			}
			BillMaterial addMaterial = new BillMaterial();//调入仓库
			BillMaterial reduceMaterial = new BillMaterial();//调出仓库
			addMaterial.setMaterialNo(materialNo);
			addMaterial.setMaterialName(materialName);
			addMaterial.setMaterialModel(specification);
			addMaterial.setCount(transferCount);
			addMaterial.setBatchNo(batchNo);
			addMaterial.setUnit(unit);
			addMaterial.setProduceDate(produceDate);
			addMaterial.setExpiryDate(expiryDate);
			addMaterial.setStockNo(toStockNo);
			addMaterial.setStockName(toStockName);
			//如果调入仓库是岗上仓库的话加上车间信息
//			if("00".equals(toStockNo)){
//				addMaterial.setWorkShop(workShop);
//			}
			addMaterial.setFlot(isFlot);
			addMaterial.setProduce(isProduce);
			addMaterialList.add(addMaterial);


			reduceMaterial.setMaterialNo(materialNo);
			reduceMaterial.setMaterialName(materialName);
			reduceMaterial.setMaterialModel(specification);
			reduceMaterial.setCount(transferCount);
			reduceMaterial.setBatchNo(batchNo);
			reduceMaterial.setUnit(unit);
			reduceMaterial.setProduceDate(produceDate);
			reduceMaterial.setExpiryDate(expiryDate);
			reduceMaterial.setStockNo(stockNo);
			reduceMaterial.setStockName(stockName);
			reduceMaterial.setProduce(isProduce);
			reduceMaterial.setFlot(isFlot);
			reduceMaterialList.add(reduceMaterial);
		}

		//库存操作
		try {
//			Map<String, Object> addMap = inventoryService.reduceInventory(user_id, userName, BillEvent.Audit, BillType.DBCK, billNo, reduceMaterialList);
//			boolean addFlag = (Boolean) addMap.get("status");
//			if (!addFlag){
//				flag = false;
//				return flag;
//			}
			//增加库存
			Map<String, Object> reduceMap = inventoryService.addInventory(user_id, userName, BillEvent.Audit, BillType.DBRK, billNo, addMaterialList);
			boolean reduceFlag = (Boolean) reduceMap.get("status");
			if (!reduceFlag){
				flag = false;
				inventoryService.addInventory(user_id, userName, BillEvent.Audit, BillType.DBRK, billNo, reduceMaterialList);
				return flag;
			}
		} catch (Exception e){
			_logger.info(e.getMessage());
		}

		//修改单据状态
		Transfer transfer = transferDao.selectOne(new QueryWrapper<Transfer>().eq("billNo", billNo));
		transfer.setStatus("audit");
		transfer.setAuditTime(new Date());
		transfer.setAuditUserName(userName);
		transfer.setUpdateUserName(userName);
		transferDao.updateById(transfer);
		return flag;
	}

	@Override
	public boolean unAuditTransfer(String userName, Long user_id, String billNo) throws Exception{
		List<BillMaterial> addMaterialList = new ArrayList<>();//调入仓库的集合
		List<BillMaterial> reduceMaterialList = new ArrayList<>();//调出仓库的集合
		List<TransferDetail> transferDetailList = transferDetailDao.selectList(new QueryWrapper<TransferDetail>().eq("billNo", billNo));

		boolean flag = true;
		for (TransferDetail data : transferDetailList){
			String materialNo = data.getMaterialNo();
			String materialName = data.getMaterialName();
			String specification = data.getSpecification();
			String batchNo = data.getFlot();
			Date produceDate = data.getProduceDate();
			Date expiryDate = data.getExpiryDate();
			String unit = data.getUnit();
			String ownerName = data.getOwnerOutId();//货主
			String stockNo = data.getSrcStockNo();
			String stockName = data.getSrcStockName();
			String toStockNo = data.getDestStockNo();
			String toStockName = data.getDestStockName();
			double transferCount = data.getFqty();
			boolean isFlot = data.getIsFlot();
			boolean isProduce = data.getIsProduce();

			BillMaterial addMaterial = new BillMaterial();//调入仓库
			BillMaterial reduceMaterial = new BillMaterial();//调出仓库
			addMaterial.setMaterialNo(materialNo);
			addMaterial.setMaterialName(materialName);
			addMaterial.setMaterialModel(specification);
			addMaterial.setCount(transferCount);
			addMaterial.setBatchNo(batchNo);
			addMaterial.setUnit(unit);
			addMaterial.setProduceDate(produceDate);
			addMaterial.setExpiryDate(expiryDate);
			addMaterial.setStockNo(stockNo);
			addMaterial.setStockName(stockName);
			addMaterial.setFlot(isFlot);
			addMaterial.setProduce(isProduce);
			addMaterialList.add(addMaterial);


			reduceMaterial.setMaterialNo(materialNo);
			reduceMaterial.setMaterialName(materialName);
			reduceMaterial.setMaterialModel(specification);
			reduceMaterial.setCount(transferCount);
			reduceMaterial.setBatchNo(batchNo);
			reduceMaterial.setUnit(unit);
			reduceMaterial.setProduceDate(produceDate);
			reduceMaterial.setExpiryDate(expiryDate);
			reduceMaterial.setStockNo(toStockNo);
			reduceMaterial.setStockName(toStockName);
			reduceMaterial.setProduce(isProduce);
			reduceMaterial.setFlot(isFlot);
			reduceMaterialList.add(reduceMaterial);
		}

		//库存操作
		try {
			Map<String, Object> addMap = inventoryService.reduceInventory(user_id, userName, BillEvent.Audit, BillType.DBCK, billNo,  reduceMaterialList  );
			boolean addFlag = (Boolean) addMap.get("status");
			if (!addFlag){
				flag = false;
				return flag;
			}
			Map<String, Object> reduceMap = inventoryService.addInventory(user_id, userName, BillEvent.Audit, BillType.DBRK, billNo, addMaterialList);
			boolean reduceFlag = (Boolean) reduceMap.get("status");
			if (!reduceFlag){
				flag = false;
				inventoryService.addInventory(user_id, userName, BillEvent.Audit, BillType.DBRK, billNo, reduceMaterialList);
				return flag;
			}
		} catch (Exception e){
			_logger.info(e.getMessage());
			throw new Exception(e.getMessage());
		}

		//修改单据状态
		Transfer transfer = transferDao.selectOne(new QueryWrapper<Transfer>().eq("billNo", billNo));
		transfer.setStatus("unAudit");
		transfer.setUpdateUserName(userName);
		transferDao.updateById(transfer);
		return flag;
	}

	@Override
	public VtuzxMap createTransferWeb(String userName, Long user_id, Map<String, Object> map) {
		List<Map<String,Object>> dataList = VtuzxUtil.getObject(map,"data");
		String billNo = IXqcConst.createBillNo(BillType.DBRK);
		String remark = VtuzxUtil.getString(map,"remark");
		List<TransferDetail> insertDetail = new ArrayList<>();//添加到详情表的数据
		for (Map<String,Object> data : dataList){
			String materialNo = VtuzxUtil.getString(data,"materialNo");
			String materialName = VtuzxUtil.getString(data,"materialName");
			String specification = VtuzxUtil.getString(data,"specification");
			String batchNo = VtuzxUtil.getString(data,"batchNo");
			Date produceDate = VtuzxUtil.parseDate(VtuzxUtil.getString(data,"produceDate"));
			Date expiryDate = VtuzxUtil.parseDate(VtuzxUtil.getString(data,"expiryDate"));
			String unit = VtuzxUtil.getString(data,"unit");
			String ownerName = VtuzxUtil.getString(data,"ownerName");//货主
			String stockNo = VtuzxUtil.getString(data,"stockNo");
			String stockName = VtuzxUtil.getString(data,"stockName");
			String toStock = VtuzxUtil.getString(data,"toStockNo");
			String[] split = toStock.split(",");
			String toStockNo = split[0];
			String toStockName = split[1];
			double transferCount = VtuzxUtil.getDouble(data,"transferCount");
			//查询调拨的物料是否启用批次
			Material material = materialDao.selectOne(new QueryWrapper<Material>().eq("FNUMBER", materialNo));
			TransferDetail transferDetail = new TransferDetail();
			transferDetail.setBillNo(billNo);
			transferDetail.setMaterialNo(materialNo);
			transferDetail.setMaterialName(materialName);
			transferDetail.setSpecification(specification);
			transferDetail.setFlot(batchNo);
			transferDetail.setProduceDate(produceDate);
			transferDetail.setExpiryDate(expiryDate);
			transferDetail.setUnit(unit);
			transferDetail.setOwnerOutId(ownerName);
			transferDetail.setSrcStockNo(stockNo);
			transferDetail.setSrcStockName(stockName);
			transferDetail.setDestStockNo(toStockNo);
			transferDetail.setDestStockName(toStockName);
			transferDetail.setFqty(transferCount);
			transferDetail.setCreateUserId(user_id);
			transferDetail.setCreateUserName(userName);
			transferDetail.setIsProduce(material.getFIsProduce());
			transferDetail.setIsFlot(material.getFIsFlot());
			insertDetail.add(transferDetail);
		}
		boolean detailSave = transferDetailService.saveOrUpdateBatch(insertDetail);
		Transfer transfer = new Transfer();
		transfer.setBillNo(billNo);
		transfer.setCreateDate(new Date());
		transfer.setCreateUserName(userName);
		transfer.setCreateUserId(user_id);
		transfer.setNote(remark);
		transfer.setStatus("save");
		boolean save = transferService.saveOrUpdate(transfer);
		return new VtuzxMap("res",save && detailSave );
	}

	@Override
	public Map<String, Object> getToadyTransfer(JSONObject map) throws Exception{
		//获取时间如果为空默认为当天,如果不为空获取参数的当天
		String time = map.getStr("time");
		Date todayTime = null;
		String startDay = "";
		String endDay = "";
		if (null != time){
			todayTime	= DateUtils.strToDate(time, "yyyy-MM-dd HH:mm:ss");
			DateTime startTime = DateUtil.beginOfDay(todayTime);
			startDay = DateUtils.dateToStr(startTime,"yyyy-MM-dd HH:mm:ss");
			DateTime endTime = DateUtil.endOfDay(todayTime);
			endDay =  DateUtils.dateToStr(endTime,"yyyy-MM-dd HH:mm:ss");
		} else {
			Date current = new Date();//当前时间
			DateTime startTime = DateUtil.beginOfDay(current);
			startDay = DateUtils.dateToStr(startTime,"yyyy-MM-dd HH:mm:ss");
			DateTime endTime = DateUtil.endOfDay(current);
			endDay =  DateUtils.dateToStr(endTime,"yyyy-MM-dd HH:mm:ss");
		}
		//根据时间段查询当天已审核的调拨单
		LambdaQueryWrapper<Transfer> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.gt(Transfer::getAuditTime,startDay)
				.le(Transfer::getAuditTime,endDay)
				.eq(Transfer::getStatus,"audit");
		List<Transfer> transfers = transferDao.selectList(queryWrapper);
		List<String> transferNoList = new ArrayList<>();
		if (transfers.size() == 0 || null == transfers){
			throw new Exception("当天没有调拨单");
		}

		List<String> taskBillNoList = new ArrayList<>();
		for (Transfer transfer : transfers){
			String billNo = transfer.getBillNo();
			if (!transferNoList.contains(billNo)){
				transferNoList.add(billNo);
			}
			String taskBillNo = transfer.getTaskBillNo();
			String[] split = taskBillNo.split(",");
			for (String str : split) {
				if (!taskBillNoList.contains(str)){
					taskBillNoList.add(str);
				}
			}
		}
		List<TransferDetail> detailList = transferDetailDao.selectList(new QueryWrapper<TransferDetail>().in("billNo", transferNoList));
		Map<String,Object> data = new HashMap<>();//key:物料编码 + 仓库 value: 重量
		List<Map<String,Object>> dataList = new ArrayList<>();//物料集合
		for (TransferDetail detail : detailList){
			String materialNo = detail.getMaterialNo();
			String workShop = detail.getWorkShop();
			double count = detail.getFqty();
			double dataCount = VtuzxUtil.getDouble(data,materialNo + "," + workShop);
			if (dataCount > 0){//map集合中有当前物料信息
				data.put(materialNo,count + dataCount);
			} else {//如果没有当前信息
				data.put(materialNo + "," + workShop,count);
				String materialName = detail.getMaterialName();
				String specification = detail.getSpecification();
				String unit = detail.getUnit();
				Map<String,Object> material = new HashMap<>();
				material.put("materialNo",materialNo);
				material.put("materialName",materialName);
				material.put("specification",specification);
				material.put("unit",unit);
				material.put("workShop",workShop);
				dataList.add(material);

			}
		}
		//循环添加物料重量信息
		for (Map<String, Object> dataMap : dataList) {
			String materialNo = dataMap.get("materialNo").toString();
			Double count = (Double) data.get(materialNo);
			dataMap.put("count",count);
		}
		Map<String,Object> resData = new HashMap<>();
		resData.put("dataList",dataList);
		resData.put("taskBillNo",taskBillNoList);
		return resData;
	}

	@Override
	public boolean removeTransfer(String billNo) {
		int res = transferDao
				.delete(new QueryWrapper<Transfer>().eq("billNo", billNo));
		int detail = transferDetailDao
				.delete(new QueryWrapper<TransferDetail>().eq("billNo", billNo));

		if (res > 0 || detail > 0){
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 生成退料的调拨单
	 * @param map
	 * @return
	 */
	@Override
	public Boolean saveReturnTransfer(JSONObject map) throws Exception {
		//获取所有的物料信息
		String billNo = IXqcConst.createBillNo(BillType.DBRK);
		List<TransferDetail> insertDetail = new ArrayList<>();//添加到调拨详情表的数据
		String userName = map.getStr("userName");//用户名
		Long userId =  map.getLong("userId");
		JSONArray jsonArray =  map.getJSONArray("material");
		String taskBillNo = map.getStr("taskBillNo");//任务单号
		boolean detailSave = true;
		boolean save = true;
		//循环物料添加调拨详情信息
		for (int i = 0; i < jsonArray.size(); i++){
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			String materialNo = jsonObject.getStr("materialNo");
			String stockNo = jsonObject.getStr("stockNo");
			StockList stockList = stockListDao.selectOne(new LambdaQueryWrapper<StockList>().eq(StockList::getFNumber, stockNo));
			String stockName = stockList.getFName();
			double count = jsonObject.getDouble("count");
			String workShop = jsonObject.getStr("workShop");//车间
			Inventory inventory = inventoryDao.selectOne(new QueryWrapper<Inventory>().eq("FMaterialNumber", materialNo)
					.eq("FStockNumber", "00"));
			if (null != inventory){
				double inventoryCount = inventory.getFqty();
				if (inventoryCount < count){
					throw new Exception(String.format("物料:%s,库存不足",materialNo));
				}
				String materialName = inventory.getFMaterialName();
				String specification = inventory.getFSpecification();
				String batchNo = inventory.getFlot();
				Date produceDate = inventory.getFProduceDate();
				Date expiryDate = inventory.getFExpiryDate();
				String unit = inventory.getFunit();
				//调出仓库都为岗上仓库
				String toStockNo = "00";
				String toStockName = "岗上仓库";
				boolean isFlot = inventory.getIsFlot();
				boolean isProduce = inventory.getIsProduce();

				TransferDetail transferDetail = new TransferDetail();
				transferDetail.setBillNo(billNo);
				transferDetail.setMaterialNo(materialNo);
				transferDetail.setMaterialName(materialName);
				transferDetail.setSpecification(specification);
				transferDetail.setFlot(batchNo);
				transferDetail.setProduceDate(produceDate);
				transferDetail.setExpiryDate(expiryDate);
				transferDetail.setUnit(unit);

				transferDetail.setSrcStockNo(toStockNo);
				transferDetail.setSrcStockName(toStockName);
				transferDetail.setDestStockNo(stockNo);//调入仓库
				transferDetail.setDestStockName(stockName);//调入仓库
				transferDetail.setWorkShop(workShop);//车间
				transferDetail.setFqty(count);
				transferDetail.setCreateUserId(userId);
				transferDetail.setCreateUserName(userName);
				transferDetail.setIsFlot(isFlot);
				transferDetail.setIsProduce(isProduce);
				insertDetail.add(transferDetail);
			} else {
				throw new Exception(String.format("货品%s不存在",materialNo));
			}


		}
		//先保存详情表数据
		detailSave = transferDetailService.saveBatch(insertDetail);
		Transfer transfer = new Transfer();
		transfer.setBillNo(billNo);
		transfer.setCreateUserName(userName);
		transfer.setCreateUserId(userId);
		transfer.setNote("退料调拨");
		transfer.setStatus("unAudit");
		transfer.setTaskBillNo(taskBillNo);
		transfer.setBatching(false);
		//保存外层表数据
		save = transferService.save(transfer);
		//审核调拨单
		try {
			auditTransfer(userName,userId,billNo);
		} catch (Exception e){
			throw new CustomException(e.getMessage());
		}


		return detailSave && save;
	}

	@Override
	public Map<String, Object> getTransferAndWorkshop(JSONObject map) throws Exception {
		//获取时间如果为空默认为当天,如果不为空获取参数的当天
		String time = map.getStr("time");
		String jsonWorkShop = map.getStr("workShop");//车间必传
		if(StringUtils.isEmpty(jsonWorkShop)){
			throw new CustomException("没有车间信息,请加上车间信息查询");
		}
		Date todayTime = null;
		String startDay = "";
		String endDay = "";
		if (null != time){
			todayTime	= DateUtils.strToDate(time, "yyyy-MM-dd HH:mm:ss");
			DateTime startTime = DateUtil.beginOfDay(todayTime);
			startDay = DateUtils.dateToStr(startTime,"yyyy-MM-dd HH:mm:ss");
			DateTime endTime = DateUtil.endOfDay(todayTime);
			endDay =  DateUtils.dateToStr(endTime,"yyyy-MM-dd HH:mm:ss");
		} else {
			Date current = new Date();//当前时间
			DateTime startTime = DateUtil.beginOfDay(current);
			startDay = DateUtils.dateToStr(startTime,"yyyy-MM-dd HH:mm:ss");
			DateTime endTime = DateUtil.endOfDay(current);
			endDay =  DateUtils.dateToStr(endTime,"yyyy-MM-dd HH:mm:ss");
		}
		//根据用料清单上的需求日期,和车间查询对应的货品信息
		//先查询外层表数据
		LambdaQueryWrapper<Proppbom> wrapper = new LambdaQueryWrapper<>();
		wrapper.ge(Proppbom::getNeedDate,startDay).le(Proppbom::getNeedDate,endDay)
				.eq(Proppbom::getWorkShop,jsonWorkShop);
		List<Proppbom> proppbomList = proppbomDao.selectList(wrapper);
		List<String> billNoList = new ArrayList<>();//用料清单单据号集合
		for (Proppbom proppbom : proppbomList){
			String billNo = proppbom.getBillNo();
			if (!billNoList.contains(billNo)){
				billNoList.add(billNo);
			}
		}
		List<Map<String,Object>> dataList = new ArrayList<>();//物料集合(返回信息)
		List<String> materialNoList = new ArrayList<>();//物料编码集合
		if (billNoList.size() == 0  || billNoList == null){
			throw new CustomException("当前时间段没有用料清单信息");
		}
		List<Proppbomlist> detailList = proppbomlistDao.selectList(new LambdaQueryWrapper<Proppbomlist>().in(Proppbomlist::getBillNo, billNoList));
		Map<String,Object> data = new HashMap<>();//key:物料编码  value: 重量
		for (Proppbomlist proppbomlist : detailList){
			String materialNo = proppbomlist.getMaterialNo();
			if(!materialNoList.contains(materialNo)){
				materialNoList.add(materialNo);
			}
			double count = proppbomlist.getNeedQty();
			double dataCount = VtuzxUtil.getDouble(data,materialNo );
			//判断当前物料是否有数量信息
			if (dataCount > 0){//map集合中有当前物料信息
				data.put(materialNo,count + dataCount);
			} else {//如果没有当前信息
				data.put(materialNo ,count);
				String materialName = proppbomlist.getMaterialName();
				String specification = proppbomlist.getSpecification();
				String unit = proppbomlist.getUnit();
				Map<String,Object> material = new HashMap<>();
				material.put("materialNo",materialNo);
				material.put("materialName",materialName);
				material.put("specification",specification);
				material.put("unit",unit);
				material.put("workShop",jsonWorkShop);
				dataList.add(material);

			}
		}


		//循环添加物料重量信息
		for (Map<String, Object> dataMap : dataList) {
			String materialNo = dataMap.get("materialNo").toString();
			Double count = (Double) data.get(materialNo);
			dataMap.put("count",count);
		}
		//根据车间和物料,仓库是岗上仓库的查询岗上库存信息,一次只查询一个车间的
		LambdaQueryWrapper<Inventory> inventoryWrapper = new LambdaQueryWrapper();
		inventoryWrapper.eq(Inventory::getFStockNumber,"00").in(Inventory::getFMaterialNumber,materialNoList)
				.eq(Inventory::getWorkShop,jsonWorkShop);
		List<Inventory> inventoryList = inventoryDao.selectList(inventoryWrapper);
		//循环添加上岗上仓库剩余数量信息
		for (Map<String, Object> dataMap : dataList){
			String materialNo = dataMap.get("materialNo").toString();
			String workShop = dataMap.get("workShop").toString();
			//根据物料和车间匹配
			for (Inventory inventory : inventoryList){
				String dutyMaterialNo = inventory.getFMaterialNumber();
				String dutyWorkShop = inventory.getWorkShop();
				Double fqty = inventory.getFqty();//岗上仓库剩余数量
				if (materialNo.equals(dutyMaterialNo) && workShop.equals(dutyWorkShop)){
					dataMap.put("dutyCount",fqty);
				}
			}
		}
		Map<String,Object> resData = new HashMap<>();
		resData.put("dataList",dataList);
		return resData;
	}

}